package org.novelhibernate.core.sqlregistry;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.novelhibernate.core.ParameterMapper;
import org.novelhibernate.util.SQLParser;

public class ProgramBasedSQLRegistry extends AbstractSQLRegistry {

	
	private SQLParser parser = SQLParser.getInstance();
	


	private static final Logger log = Logger.getLogger(ProgramBasedSQLRegistry.class);
	
	@Override
	public synchronized void registerCreateSql(String sql, Class<?> target) {


		log.debug("[Program based regisration]register in advance for insert SQL: " + sql);
		try {

			registry.put(sql.replaceAll("\\s*", ""), registerInsertStatement(target));

		} catch (Throwable t) {

			t.printStackTrace();
		}
	}

	@Override
	public synchronized void registerUpdateSql(String sql, Class<?> target, ParameterMapper[] mappers) {

		log.debug("[Program based regisration]register in advance for update SQL: " + sql);
		
		
		try {

			Object[] parameters = parser.parseUpdateSQL(sql, target);
			registry.put(sql.replaceAll("\\s*", ""), registerUpdateAndDeleteStatement(target, parameters, mappers));

		} catch (Throwable t) {

			t.printStackTrace();
		}

	}

	
	@Override
	public synchronized void registerDeleteSql(String sql, Class<?> target, ParameterMapper[] mappers) {

		
		log.debug("[Program based regisration]register in advance for delete SQL: " + sql);
		
		try {

			List<Integer> restrict = new ArrayList<Integer>();
			if (null != mappers)
				for (ParameterMapper mapper : mappers)
					restrict.add(mapper.getIndex());
			
			Object[] parameters = parser.parseDeleteSQL(sql, restrict);
			registry.put(sql.replaceAll("\\s*", ""), registerUpdateAndDeleteStatement(target, parameters, mappers));

		} catch (Throwable t) {

			t.printStackTrace();
		}

	}
}
